package cn.jane.bigevent.controller;

import cn.jane.bigevent.entity.Result;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件模块
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Value("${storage.path-prefix}")
    private String pathPrefix;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result<Object> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        if (!StringUtils.hasLength(originalFilename)) {
            return Result.error("缺少文件名");
        }
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID() + extension;
        String filePath = pathPrefix + filename;
        file.transferTo(new File(filePath));
        String fileUrl = "http://127.0.0.1:8080/file/download/" + filename;
        return Result.success(fileUrl);
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{filename}")
    public ResponseEntity<Resource> download(@PathVariable String filename) {
        try {
            Path filePath = Paths.get(pathPrefix).resolve(filename).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (!(resource.exists() || resource.isReadable())) {
                log.error("文件 {} 不存在", filename);
                return ResponseEntity.notFound().build();
            }

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } catch (MalformedURLException e) {
            log.error(e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
}
